package com.hd.trans.utils

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioDeviceInfo
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.os.Build
import android.os.Handler
import com.hd.trans.utils.thread.ThreadWrapper
import java.util.Timer
import java.util.TimerTask

class AudioManagerWrapper(context: Context) {
    private val mAudioManager:AudioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
    private var mAudioFocusRequest: AudioFocusRequest? = null
    private var mAudioFocusListener : AudioManager.OnAudioFocusChangeListener? = null

    private var mAudioFocus = AudioManager.AUDIOFOCUS_LOSS

    //监听设备插入的定时器
    private var mAudioManagerTimer: Timer? = null
    private var mDevicesListener: ((Boolean) -> Unit)? = null
    private var mMusicPlayListener: ((Boolean) -> Unit)? = null

    private var isDevicesConnected:Boolean? = null
    private var isMusicPlaying:Boolean? = null

    fun requestTheAudioFocus(listener:AudioManager.OnAudioFocusChangeListener): Int{
        return requestTheAudioFocus(listener,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
    }

    /**
     * 请求音频焦点
     */
    fun requestTheAudioFocus(listener:AudioManager.OnAudioFocusChangeListener,focusGain:Int): Int{
        releaseTheAudioFocus()
        mAudioFocusListener = listener
        val mAttribute = AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()

        //android 版本 8.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mAudioFocusRequest = AudioFocusRequest.Builder(focusGain)
                .setWillPauseWhenDucked(true)
                .setAcceptsDelayedFocusGain(true)
                .setOnAudioFocusChangeListener(listener, Handler())
                .setAudioAttributes(mAttribute)
                .build()
        }

        val audioFocus: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mAudioManager.requestAudioFocus(mAudioFocusRequest!!)
        } else {
            mAudioManager.requestAudioFocus(listener, AudioManager.STREAM_MUSIC, focusGain)
        }

        mAudioFocus = audioFocus

        return audioFocus
    }

    /**
     * 释放焦点
     */
    fun releaseTheAudioFocus() {
        if (mAudioFocus == AudioManager.AUDIOFOCUS_LOSS) {
            return
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mAudioFocusRequest?.let {
                mAudioManager.abandonAudioFocusRequest(it)
            }
            mAudioFocusRequest = null
        } else {
            mAudioFocusListener?.let {
                mAudioManager.abandonAudioFocus(it)
            }
            mAudioFocusListener = null
        }
    }

    /**
     * 耳机是否插入
     * @return 插入耳机返回true,否则返回false
     */
    fun isWiredHeadsetOn(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val devices = mAudioManager.getDevices(AudioManager.GET_DEVICES_INPUTS)
            for (device in devices) {
                val hasHeadset = when(device.type){
                    AudioDeviceInfo.TYPE_WIRED_HEADSET //有线耳麦
                        ,AudioDeviceInfo.TYPE_WIRED_HEADPHONES //有线耳机
                        ,AudioDeviceInfo.TYPE_BLUETOOTH_SCO //蓝牙耳麦
                        ,AudioDeviceInfo.TYPE_BLUETOOTH_A2DP //蓝牙耳机
                        ,AudioDeviceInfo.TYPE_USB_HEADSET //USB耳麦
                    -> true
                    else -> false
                }
                if (hasHeadset) {
                    return true
                }
            }
        }
        return false
    }

    /**
     * 是否正在播放音视频
     */
    fun isMusicPlaying(): Boolean {
        return mAudioManager.isMusicActive
    }

    /**
     * 设置设备连接监听
     */
    fun setDevicesListener(listener: ((Boolean) -> Unit)?) {
        mDevicesListener = listener
        if (listener == null){
            return
        }
        initAudioManagerTimer()
    }

    /**
     * 设置音乐播放监听
     */
    fun setMusicPlayListener(listener: ((Boolean) -> Unit)?) {
        mMusicPlayListener = listener
        if (listener == null){
            return
        }
        initAudioManagerTimer()
    }

    private fun initAudioManagerTimer(){
        if (mAudioManagerTimer != null)
            return

        mAudioManagerTimer = Timer().apply {
            schedule(object : TimerTask() {
                override fun run() {
                    if (mDevicesListener != null || mMusicPlayListener != null){
                        ThreadWrapper.uiThreadExecute {
                            mDevicesListener?.let {
                                val isConnected = isWiredHeadsetOn()
                                if (isConnected != isDevicesConnected){
                                    isDevicesConnected = isConnected
                                    it.invoke(isConnected)
                                }
                            }

                            mMusicPlayListener?.let {
                                val isPlay = isMusicPlaying()
                                if (isPlay != isMusicPlaying){
                                    isMusicPlaying = isPlay
                                    it.invoke(isPlay)
                                }
                            }
                        }
                    }
                }
            }, 0, 800)
        }
    }

    private fun releaseAudioManagerTimer(){
        mAudioManagerTimer?.cancel()
        mAudioManagerTimer?.purge()
        mAudioManagerTimer = null
    }

    val isSpeakerphoneOn:Boolean
        get() = mAudioManager.isSpeakerphoneOn

    /**
     * 切换到扬声器播放
     */
    fun changeToSpeaker() {
        if (mAudioFocus == AudioManager.AUDIOFOCUS_LOSS || mAudioManager.isSpeakerphoneOn) {
            return
        }
        //因为可能会比较耗时，所以放到子线程中执行
        ThreadWrapper.ioThreadExecute {
            mAudioManager.mode = AudioManager.MODE_NORMAL
            mAudioManager.isSpeakerphoneOn = true
        }
    }

    /**
     * 切换到听筒播放
     */
    fun changeToEarpiece() {
        if (mAudioFocus == AudioManager.AUDIOFOCUS_LOSS || !mAudioManager.isSpeakerphoneOn) {
            return
        }
        //因为可能会比较耗时，所以放到子线程中执行
        ThreadWrapper.ioThreadExecute {
            mAudioManager.mode = AudioManager.MODE_IN_COMMUNICATION
            mAudioManager.isSpeakerphoneOn = false
        }
    }

    fun releaseAll(){
        //切换回扬声器播放
        changeToSpeaker()
        //释放焦点
        releaseTheAudioFocus()
        //释放设备连接监听
        mDevicesListener = null
        //释放音乐播放监听
        mMusicPlayListener = null
        releaseAudioManagerTimer()
    }

}